package com.xlh.util;

import com.xlh.exception.common.GlobalException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * 数据库连接配置
 * <p>
 * Created by lx on 2018/7/20.
 */
public class JDBCTemplateUtil {

    public static JdbcTemplate getTemplate(String ip, String port, String dbName, String userName, String password) {
        return new JdbcTemplate(getMysqlDataSource(ip, port, dbName, userName, password));
    }

    private static DataSource getMysqlDataSource(
            String ip, String port, String dbName, String userName, String password) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(
                StringUtils.join(
                        "jdbc:mysql://", ip, ":", port, "/", dbName,
                        "?useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull" +
                                "&allowMultiQueries=true"
                ),
                userName,
                password);
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

    public static JdbcTemplate getJdbcTemplate(
            String ip, String port, String dbName, String userName, String password) {
        try {
            return JDBCTemplateUtil.getTemplate(ip, port, dbName, userName, password);
        } catch (BadSqlGrammarException e) {
            throw new GlobalException(ip + "数据库连接失败。未知错误");
        } catch (CannotGetJdbcConnectionException e) {
            throw new GlobalException(ip + "连接数据库失败");
        } catch (UncategorizedSQLException e) {
            throw new GlobalException(ip + "未知错误2");
        }
    }

}
